package cn.kgc.itrip.auth.controller;

import cn.kgc.itrip.auth.service.TokenService;
import cn.kgc.itrip.auth.service.UserService;
import cn.kgc.itrip.beans.dto.Dto;
import cn.kgc.itrip.beans.pojo.ItripUser;
import cn.kgc.itrip.beans.vo.ItripTokenVO;
import cn.kgc.itrip.utils.*;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;

@RestController
@RequestMapping("/api")
public class LoginController {

    @Resource
    private UserService userService;
    @Resource
    private TokenService tokenService;
    @Resource
    private ValidationToken validationToken;

    /**
     * 用户注销
     * @param token
     * @return
     */
    @RequestMapping(value = "/logout",method = RequestMethod.GET)
    public Dto doLogout(@RequestHeader String token){
        try{
            // 直接删除Token
            tokenService.delToken(token);
            // 注销成功
            return DtoUtil.returnSuccess();
        } catch (Exception e) {
            e.printStackTrace();
            return DtoUtil.returnFail("注销失败！",ErrorCode.AUTH_UNKNOWN);
        }
    }

    /**
     * 用户Token置换
     * @param token
     * @param userAgent
     * @return
     */
    @RequestMapping(value = "/retoken",method = RequestMethod.POST)
    public Dto doRetoken(@RequestHeader String token,@RequestHeader("User-Agent") String userAgent){
        try {
            // 用户未登录(Token过期)
            ItripUser currentUser = validationToken.getCurrentUser(TokenService.TOKEN_KEY_PREFIX+token);
            if(EmptyUtils.isEmpty(currentUser)){
                return DtoUtil.returnFail("用户还未登录或Token已过期！",ErrorCode.AUTH_TOKEN_INVALID);
            }
            // Token应该在1.5小时后才可以进行置换(Bug：前端在遇到错误时 自动弹出对话框)
            if(!tokenService.checkTokenTimeOut(token,userAgent)){
                return DtoUtil.returnFail("",ErrorCode.AUTH_RETOKEN_NEED_WAIT);
            }
            // Token进行置换
            String newToken = tokenService.refreshToken(token,userAgent,currentUser);
            ItripTokenVO tokenVO = new ItripTokenVO(newToken,
                                                    System.currentTimeMillis() + TokenService.TOKEN_TIME_OUT * 1000,
                                                    System.currentTimeMillis());
            return DtoUtil.returnDataSuccess(tokenVO);
        } catch (Exception e) {
            e.printStackTrace();
            return DtoUtil.returnFail("置换Token失败！",ErrorCode.AUTH_UNKNOWN);
        }
    }

    /**
     * 自注册用户登录
     * @param name
     * @param password
     * @param userAgent
     * @return
     */
    @RequestMapping(value = "/dologin",method = RequestMethod.POST)
    public Dto doLogin(@RequestParam String name, @RequestParam String password, @RequestHeader("User-Agent") String userAgent){
        try {
            // 表单验证
            if(!ValidateUtil.validPhone(name)){
                return DtoUtil.returnFail("手机号格式错误！",ErrorCode.AUTH_PARAMETER_ERROR);
            }
            // 帐号和密码验证
            ItripUser itripUser = userService.login(name,password);
            if(EmptyUtils.isEmpty(itripUser)){
                return DtoUtil.returnFail("用户名或密码错误！",ErrorCode.AUTH_USER_PASSWORD_ERROR);
            }else{
                // 是否激活
                if(itripUser.getActivated() == 0){
                    return DtoUtil.returnFail("用户还未激活！请先去激活！",ErrorCode.AUTH_USER_NEED_ACTIVATE);
                }
            }
            // 登录成功 使用Token存储部分用户信息
            String token = tokenService.genToken(itripUser,userAgent);
            // 保存Token 帐号登录互斥
            tokenService.saveToken(token,itripUser,userAgent);
            ItripTokenVO tokenVO = new ItripTokenVO(token,
                                        System.currentTimeMillis() + TokenService.TOKEN_TIME_OUT * 1000,
                                        System.currentTimeMillis());
            return DtoUtil.returnDataSuccess(tokenVO);
        } catch (Exception e) {
            e.printStackTrace();
            return DtoUtil.returnFail("登录失败！请重试！", ErrorCode.AUTH_UNKNOWN);
        }
    }


}
